package com.zhxs.nfcscan.view;

import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.hjq.http.EasyHttp;
import com.hjq.http.body.JsonRequestBody;
import com.hjq.http.listener.HttpCallbackProxy;
import com.hjq.http.request.BodyRequest;
import com.tencent.mmkv.MMKV;
import com.yc.ycthreadpoollib.PoolThread;
import com.zhhd.base.BaseDialog;
import com.zhhd.libdb.PatrolRecord;
import com.zhhd.libdb.ProjectDatabase;
import com.zhxs.nfcscan.R;
import com.zhxs.nfcscan.base.app.AppActivity;
import com.zhxs.nfcscan.base.app.AppApplication;
import com.zhxs.nfcscan.base.dialog.MessageDialog;
import com.zhxs.nfcscan.base.http.api.NetworkTestApi;
import com.zhxs.nfcscan.base.http.api.PatrolRecordApi;
import com.zhxs.nfcscan.base.http.api.PersonInfoApi;
import com.zhxs.nfcscan.base.http.api.UpdatePatrolApi;
import com.zhxs.nfcscan.base.http.entity.PersonInfo;
import com.zhxs.nfcscan.base.http.model.HttpData;
import com.zhxs.utils.LogUtil;
import com.zhxs.utils.ThreadPoolHelper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import io.reactivex.rxjava3.disposables.CompositeDisposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;

/**
 * 数据同步页面
 */
public class DataSyncActivity extends AppActivity {
    
    // UI组件
    private Button btnPullPersonnel;
    private Button btnPullPatrolPlan;
    private Button btnUploadPatrolData;
    private Button btnCheckNetwork;
    private TextView tvOperationResult;
    private ScrollView scrollView;
    
    // 状态变量
    private boolean isOperationInProgress = false;
    private SimpleDateFormat dateFormat;
    private CompositeDisposable compositeDisposable;
    private MMKV mmkv;
    private String serverUrl;
    
    @Override
    protected int getLayoutId() {
        return R.layout.activity_data_sync;
    }
    
    @Override
    protected void initView() {
        // 初始化UI组件
        btnPullPersonnel = findViewById(R.id.btn_pull_personnel);
        btnPullPatrolPlan = findViewById(R.id.btn_pull_patrol_plan);
        btnUploadPatrolData = findViewById(R.id.btn_upload_patrol_data);
        btnCheckNetwork = findViewById(R.id.btn_check_network);
        tvOperationResult = findViewById(R.id.tv_operation_result);
        scrollView = findViewById(R.id.scroll_view);
        
        // 设置点击监听器
        btnPullPersonnel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPullPersonnelClick();
            }
        });
        
        btnPullPatrolPlan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onPullPatrolPlanClick();
            }
        });
        
        btnUploadPatrolData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onUploadPatrolDataClick();
            }
        });
        
        btnCheckNetwork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCheckNetworkClick();
            }
        });
    }
    
    @Override
    protected void initData() {
        compositeDisposable = new CompositeDisposable();
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        mmkv = MMKV.defaultMMKV();
        
        // 初始化结果显示区域
        appendResult(getString(R.string.data_sync_ready));
    }

    @Override
    protected void onResume() {
        super.onResume();
        serverUrl = mmkv.decodeString(AppApplication.KEY_SERVER_URL, AppApplication.DEFAULT_SERVER_URL);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (compositeDisposable != null && !compositeDisposable.isDisposed()) {
            compositeDisposable.dispose();
        }
    }
    
    /**
     * 拉取人员信息
     */
    private void onPullPersonnelClick() {
        if (isOperationInProgress) {
            Toast.makeText(this, getString(R.string.operation_in_progress), Toast.LENGTH_SHORT).show();
            return;
        }
        appendResult("开始拉取人员信息...");
        getPersonInfo();
    }
    
    /**
     * 拉取巡更计划
     */
    private void onPullPatrolPlanClick() {
        if (isOperationInProgress) {
            Toast.makeText(this, getString(R.string.operation_in_progress), Toast.LENGTH_SHORT).show();
            return;
        }
        appendResult("开始拉取巡更计划...");
        getPatrolRecord();
    }
    
    /**
     * 上传巡更数据
     */
    private void onUploadPatrolDataClick() {
        if (isOperationInProgress) {
            Toast.makeText(this, getString(R.string.operation_in_progress), Toast.LENGTH_SHORT).show();
            return;
        }
        


        // 在子线程中执行数据库操作
        PoolThread dbExecutor = ThreadPoolHelper.Companion.get().getExecutor();
        dbExecutor.execute(new Runnable() {
            @Override
            public void run() {
                // 查询数据库中的巡更数据
                List<PatrolRecord> datas = ProjectDatabase.getInstance(DataSyncActivity.this)
                        .getPatrolRecordDao().getAllPatrolRecord();
                if (datas!=null && !datas.isEmpty()){
                    appendResult("开始上传巡更数据...");
                    String json = new Gson().toJson(datas);
                    EasyHttp.post(DataSyncActivity.this).server(serverUrl)
                            .api(new UpdatePatrolApi())
                            .body(new JsonRequestBody(json))
                            .request(new HttpCallbackProxy<HttpData<String>>(DataSyncActivity.this) {

                                @Override
                                public void onHttpSuccess(@NonNull HttpData<String> result) {
                                    super.onHttpSuccess(result);
                                    if (result.getCode() == 0){
                                        isOperationInProgress = false;
                                        updateButtonStates();
                                        appendResult("共上传 " + datas.size() + " 条巡更计划");
                                    }
                                }

                                @Override
                                public void onHttpFail(@NonNull Throwable throwable) {
                                    super.onHttpFail(throwable);
                                    isOperationInProgress = false;
                                    updateButtonStates();

                                    appendResult("上传失败");
                                }

                            });
                } else {
                    appendResult("本地没有巡更数据");
                }

            }
        });



//        simulateNetworkOperationRx("上传巡更数据", new Runnable() {
//            @Override
//            public void run() {
//                appendResult("巡更数据上传完成");
//                Toast.makeText(DataSyncActivity.this, getString(R.string.patrol_data_upload_success), Toast.LENGTH_SHORT).show();
//            }
//        });
    }
    
    /**
     * 检查网络状态
     */
    private void onCheckNetworkClick() {
        isOperationInProgress = true;
        updateButtonStates();
        EasyHttp.get(this).server(serverUrl)
//        EasyHttp.get(this).server("http://192.168.2.38:8080/police")
                .api(new NetworkTestApi())
                .request(new HttpCallbackProxy<HttpData<String>>(this) {

                    @Override
                    public void onHttpSuccess(HttpData<String> result) {
                        super.onHttpSuccess(result);
                        if (result.getCode() == 0){
                            isOperationInProgress = false;
                            updateButtonStates();

                            appendResult("服务器连接成功");
                            appendResult("网络状态检查完成");
                        }
                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {
                        super.onHttpFail(throwable);
                        isOperationInProgress = false;
                        updateButtonStates();
                        appendResult("网络连接异常，请检查网线是否正确连接，IP地址是否正确配置！");
                    }
                });
    }

    /**
     * 获取人员基础信息
     */
    private void getPersonInfo() {
        isOperationInProgress = true;
        updateButtonStates();
        EasyHttp.get(this).server(serverUrl)
                .api(new PersonInfoApi())
                .request(new HttpCallbackProxy<HttpData<List<PersonInfo>>>(this) {

                    @Override
                    public void onHttpSuccess(HttpData<List<PersonInfo>> result) {
                        super.onHttpSuccess(result);
                        if (result.getCode() == 0){
                            List<PersonInfo> datas = result.getData();
                            if (datas!=null && !datas.isEmpty()){
                                String json = new Gson().toJson(datas);
                                mmkv.putString(AppApplication.KEY_PERSON_LIST_INFO,json);
                                appendResult("人员信息拉取成功:共"+datas.size()+"条");
                                isOperationInProgress = false;
                                updateButtonStates();
                            }
                        }
                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {
                        super.onHttpFail(throwable);
                        isOperationInProgress = false;
                        updateButtonStates();
                        appendResult("人员信息拉取失败");
                    }
                });
    }


    /**
     * 获取当天巡更点
     */
    private void getPatrolRecord() {
        isOperationInProgress = true;
        updateButtonStates();
        EasyHttp.get(this).server(serverUrl)
                .api(new PatrolRecordApi())
                .request(new HttpCallbackProxy<HttpData<List<PatrolRecord>>>(this) {
                    @Override
                    public void onHttpSuccess(HttpData<List<PatrolRecord>> result) {
                        if (result.getCode() == 0){
                            List<PatrolRecord> datas = result.getData();
                            if (datas!=null && !datas.isEmpty()){
                                // 在子线程中查询本地数据库
                                PoolThread executor = ThreadPoolHelper.Companion.get().getExecutor();
                                executor.setName("查询本地巡更数据");
                                executor.execute(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 查询本地数据库是否有记录
                                        List<PatrolRecord> localRecords = ProjectDatabase.getInstance(DataSyncActivity.this)
                                                .getPatrolRecordDao().getAllPatrolRecord();
                                        
                                        // 在主线程中显示对话框
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (localRecords != null && !localRecords.isEmpty()) {
                                                    // 本地有数据，弹出确认对话框
                                                    new MessageDialog.Builder(DataSyncActivity.this)
                                                            .setMessage("本地存在未上传数据，确定要覆盖吗？")
                                                            .setListener(new MessageDialog.OnListener() {
                                                                @Override
                                                                public void onConfirm(BaseDialog dialog) {
                                                                    // 在子线程中执行数据库操作
                                                                    PoolThread dbExecutor = ThreadPoolHelper.Companion.get().getExecutor();
                                                                    dbExecutor.execute(new Runnable() {
                                                                        @Override
                                                                        public void run() {
                                                                            // 删除本地数据
                                                                            ProjectDatabase.getInstance(DataSyncActivity.this)
                                                                                    .getPatrolRecordDao().deleteAllPatrolRecord();
                                                                            // 保存新数据
                                                                            ProjectDatabase.getInstance(DataSyncActivity.this)
                                                                                    .getPatrolRecordDao().insertPatrolRecords(datas);
                                                                            
                                                                            // 在主线程更新UI
                                                                            runOnUiThread(new Runnable() {
                                                                                @Override
                                                                                public void run() {
                                                                                    appendResult("巡更计划拉取成功");
                                                                                    isOperationInProgress = false;
                                                                                    updateButtonStates();
                                                                                    appendResult("共保存 " + datas.size() + " 条巡更计划");
                                                                                }
                                                                            });
                                                                        }
                                                                    });
                                                                }

                                                                @Override
                                                                public void onCancel(BaseDialog dialog) {
                                                                    MessageDialog.OnListener.super.onCancel(dialog);
                                                                    appendResult("巡更计划拉取失败");
                                                                    isOperationInProgress = false;
                                                                    updateButtonStates();
                                                                }

                                                            })
                                                            .addOnDismissListener(new BaseDialog.OnDismissListener() {
                                                                @Override
                                                                public void onDismiss(BaseDialog dialog) {
                                                                    appendResult("巡更计划拉取失败");
                                                                    isOperationInProgress = false;
                                                                    updateButtonStates();
                                                                }
                                                            }).show();
                                                } else {
                                                    // 本地没有数据，直接保存
                                                    PoolThread dbExecutor = ThreadPoolHelper.Companion.get().getExecutor();
                                                    dbExecutor.execute(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            // 保存新数据
                                                            ProjectDatabase.getInstance(DataSyncActivity.this)
                                                                    .getPatrolRecordDao().insertPatrolRecords(datas);
                                                            
                                                            // 在主线程更新UI
                                                            runOnUiThread(new Runnable() {
                                                                @Override
                                                                public void run() {
                                                                    appendResult("巡更计划拉取成功");
                                                                    isOperationInProgress = false;
                                                                    updateButtonStates();
                                                                    appendResult("共保存 " + datas.size() + " 条巡更计划");
                                                                }
                                                            });
                                                        }
                                                    });
                                                }
                                            }
                                        });
                                    }
                                });
                            } else {
                                isOperationInProgress = false;
                                updateButtonStates();
                                appendResult("服务器返回数据为空");
                            }
                        }
                    }

                    @Override
                    public void onHttpFail(@NonNull Throwable throwable) {
                        super.onHttpFail(throwable);
                        isOperationInProgress = false;
                        updateButtonStates();
                        appendResult("巡更计划拉取失败: " + throwable.getMessage());
                    }
                });
    }

    /**
     * 更新按钮状态
     */
    private void updateButtonStates() {
        boolean enabled = !isOperationInProgress;
        btnPullPersonnel.setEnabled(enabled);
        btnPullPatrolPlan.setEnabled(enabled);
        btnUploadPatrolData.setEnabled(enabled);
        btnCheckNetwork.setEnabled(enabled);
    }
    
    /**
     * 添加操作结果到显示区域
     */
    private void appendResult(String message) {
        String timestamp = dateFormat.format(new Date());
        String result = "[" + timestamp + "] " + message + "\n";
        
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvOperationResult.append(result);
                // 滚动到底部
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                    }
                });
            }
        });
        
        LogUtil.d("DataSync: " + message);
    }
    
    /**
     * 清空操作结果
     */
    public void clearResults() {
        tvOperationResult.setText("");
        appendResult(getString(R.string.operation_result_cleared));
    }

}
